﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using GNSCore.Helpers;
using System.Threading;
using GNSCore.Model;
using GNSCore.Settings;
using ThirdServices.AlertModel.Factory.Entities.DTO;

namespace GNSCore.Helpers
{
    /// <summary>
    /// For mail setting, sending mail
    /// </summary>
    public static class MailHelper
    {
        private static void SendMail(object message)
        {
            try
            {
                SmtpClient smtp = new SmtpClient
                                      {
                                          //                                    UseDefaultCredentials = true,
                                          EnableSsl = MailSettings.UseSSL
                                      };
                smtp.Send((MailMessage)message);
            }
            catch (Exception ex)
            {
                //todo write to the log
            }
        }

        /// <summary>
        /// Sends notification email to the specefied user
        /// </summary>
        /// <param name="userReceiver">User to receive emails</param>
        /// <param name="alerts">Alerts for this user</param>
        public static void SendNotificationEmail(User userReceiver, List<BaseAlert> alerts)
        {
            bool useSSL = MailSettings.UseSSL;
            MailMessage message = new MailMessage();
            message.To.Add(userReceiver.Membership.Email);
            message.IsBodyHtml = true;
            //todo localize
            message.Subject = "Global Notification System";
            message.Body = FormatAlertsToMailMessage(alerts);
            Thread thread = new Thread(new ParameterizedThreadStart(SendMail));
            thread.Start(message);
        }

        private static string FormatAlertsToMailMessage(List<BaseAlert> alerts)
        {
            ///todo localize this message
            string message = "There are some alerts in your region:<br />";
            foreach (BaseAlert alert in alerts)
            {
                message += string.Format("<h4>Alert:</h4> <br />{0}<br />",alert.NotificationDescription);
            }
            return message;
        }
    }
}